using System.IO;
using System.Threading;

namespace winsw
{
	public class TimeBasedRollingLogAppender : AbstractFileLogAppender
	{
		private string pattern;

		private int period;

		public TimeBasedRollingLogAppender(string logDirectory, string baseName, string pattern, int period)
			: base(logDirectory, baseName)
		{
			this.pattern = pattern;
			this.period = period;
		}

		public override void log(Stream outputStream, Stream errorStream)
		{
			new Thread((ThreadStart)delegate
			{
				CopyStreamWithDateRotation(outputStream, ".out.log");
			}).Start();
			new Thread((ThreadStart)delegate
			{
				CopyStreamWithDateRotation(errorStream, ".err.log");
			}).Start();
		}

		private void CopyStreamWithDateRotation(Stream data, string ext)
		{
			PeriodicRollingCalendar periodicRollingCalendar = new PeriodicRollingCalendar(pattern, period);
			periodicRollingCalendar.init();
			byte[] array = new byte[1024];
			FileStream fileStream = new FileStream(base.BaseLogFileName + "_" + periodicRollingCalendar.format + ext, FileMode.Append);
			while (true)
			{
				bool flag = true;
				int num = data.Read(array, 0, array.Length);
				if (num == 0)
				{
					break;
				}
				if (periodicRollingCalendar.shouldRoll)
				{
					int offset = 0;
					bool flag2 = false;
					for (int i = 0; i < num; i++)
					{
						if (array[i] == 10)
						{
							fileStream.Write(array, offset, i + 1);
							fileStream.Close();
							offset = i + 1;
							fileStream = new FileStream(base.BaseLogFileName + "_" + periodicRollingCalendar.format + ext, FileMode.Create);
							flag2 = true;
						}
					}
					if (!flag2)
					{
						fileStream.Write(array, 0, num);
						fileStream.Close();
						fileStream = new FileStream(base.BaseLogFileName + "_" + periodicRollingCalendar.format + ext, FileMode.Create);
					}
				}
				else
				{
					fileStream.Write(array, 0, num);
				}
				fileStream.Flush();
			}
			data.Close();
			fileStream.Close();
		}
	}
}
